package com.yeyks.commonReference.service.consumer.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yeyks.account.dal.domain.AccountInfo;
import com.yeyks.common.ajax.AjaxResponseBody;
import com.yeyks.common.appcommon.dto.platform.AppMemberCardDTO;
import com.yeyks.common.appcommon.param.platform.QueryMinMemberCardParam;
import com.yeyks.common.appcommon.result.CommonPage;
import com.yeyks.common.appcommon.result.CommonResult;
import com.yeyks.common.base.Arguments;
import com.yeyks.common.base.PageResult;
import com.yeyks.common.constants.AccountType;
import com.yeyks.common.constants.ConfigKey;
import com.yeyks.common.constants.MessageTemplate;
import com.yeyks.common.constants.RechargeRecordStatus;
import com.yeyks.common.dto.AccountCardDTO;
import com.yeyks.common.dto.MemberCardSelectAllDTO;
import com.yeyks.common.dto.member.MemberCardSelectChoiceAllDTO;
import com.yeyks.common.dto.member.MemberCardSelectServerAllDTO;
import com.yeyks.common.em.RechangeRecordEnum;
import com.yeyks.common.em.UserMemberCardBillType;
import com.yeyks.common.em.mattress.OrderInfoMattressPayTypeEnum;
import com.yeyks.common.em.vip.VipCardTypeEnum;
import com.yeyks.common.exception.OftenFiledException;
import com.yeyks.common.exception.ServiceException;
import com.yeyks.common.param.member.*;
import com.yeyks.common.result.member.MemberCardHelpPayListResult;
import com.yeyks.common.utils.*;
import com.yeyks.common.utils.apputil.bean.MyBeanUtils;
import com.yeyks.commonReference.service.config.ConfigService;
import com.yeyks.commonReference.service.consumer.MemberCardService;
import com.yeyks.commonReference.service.consumer.MessageNoticeTemplateService;
import com.yeyks.commonReference.service.vip.AccountVipSalerRelationService;
import com.yeyks.consumer.dal.dao.MemberCardDetailMapper;
import com.yeyks.consumer.dal.dao.MemberCardMapper;
import com.yeyks.consumer.dal.dao.MessageNoticeTemplateMapper;
import com.yeyks.consumer.dal.dao.UserMemberCardBillMapper;
import com.yeyks.consumer.dal.domain.*;
import com.yeyks.consumer.dto.CardNoResult;
import com.yeyks.consumer.param.MemberCardCheckParam;
import com.yeyks.consumer.param.MemberCardTypeParam;
import com.yeyks.consumer.param.UserMemberCard.UserMemberCardAddAmountParam;
import com.yeyks.consumer.service.MemberCardDetailService;
import com.yeyks.consumer.service.RechargeRecordService;
import com.yeyks.commonReference.service.consumer.UserMemberCardService;
import com.yeyks.hotel.dal.dao.HotelInfoMapper;
import com.yeyks.hotel.dal.domain.HotelInfo;
import com.yeyks.order.dal.domain.OrderHead;
import com.yeyks.vip.dal.domain.AccountVipSalerRelation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


/**
 * <p>
 * 会员卡表 服务实现类
 * </p>
 *
 * @author yun
 * @since 2019-06-25
 */
@Service
@Slf4j
public class MemberCardServiceImpl extends ServiceImpl<MemberCardMapper, MemberCard> implements MemberCardService {


    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private MemberCardMapper memberCardMapper;
    @Autowired
    private MemberCardDetailMapper memberCardDetailMapper;
    @Autowired
    private HotelInfoMapper hotelInfoMapper;
    @Autowired
    private UserMemberCardService userMemberCardService;
    @Autowired
    private UserMemberCardBillMapper userMemberCardBillMapper;
    @Autowired
    private MessageNoticeTemplateMapper messageNoticeTemplateMapper;
    @Autowired
    private ConfigService configService;
    @Autowired
    private AccountVipSalerRelationService accountVipSalerRelationService;
    @Autowired
    private RechargeRecordService rechargeRecordService;
    @Autowired
    private MessageNoticeTemplateService templateService;
    @Autowired
    private MemberCardDetailService memberCardDetailService;

    private Pattern pattern = Pattern.compile("^[0-9]{16}$");
    private String redisLockVipCardOperating = "redislock:MemberCardService:VipCardOperating";

    //检查卡是否已出售
    @Override
    public Boolean checkCardEnable(MemberCardCheckParam param) {
        MemberCard memberCard = getOne(
                new QueryWrapper<MemberCard>()
                        .eq(MemberCard.CARD_NO, param.getCardNo())
                        .eq(MemberCard.CARD_TYPE, param.getCardType())
                        .last("limit 1")
        );
        if (Objects.isNull(memberCard)) {
            throw new ServiceException("卡号输入有误，重新输入");
        }
        if (Objects.equals(memberCard.getEnable(), 1)) {
            throw new ServiceException("该会员卡已售出");
        }
        if (!Objects.equals(memberCard.getStatus(), 1)) {
            throw new ServiceException("该会员卡未绑定酒店");
        }
        return true;
    }

    @Override
    public AjaxResponseBody selectForHotelManagerPage(MemberCardQueryParam memberCardQueryParam) {
        Long count = memberCardMapper.countCardByHotelId(memberCardQueryParam.getHotelId(),
                memberCardQueryParam.getCardType());
        AjaxResponseBody ajaxResponseBody = selectAll(memberCardQueryParam);
        HashMap<String, Object> map = new HashMap<>();
        map.put("count", count);
        map.put("list", ajaxResponseBody.getBody());
        return AjaxResponseBody.success(map);
    }

    //查询
    @Override
    public AjaxResponseBody selectAll(MemberCardQueryParam memberCardQueryParam) {
        if (null == memberCardQueryParam.getPageNum()) {
            memberCardQueryParam.setPageNum(1);
        }
        if (null == memberCardQueryParam.getPageSize()) {
            memberCardQueryParam.setPageSize(10);
        }
        PageHelper.startPage(memberCardQueryParam.getPageNum(), memberCardQueryParam.getPageSize());
        List<MemberCardSelectAllDTO> mapList = memberCardMapper.selectForManagementPage(memberCardQueryParam.getCardNo(),
                memberCardQueryParam.getHotelId(),
                memberCardQueryParam.getStatus(),
                memberCardQueryParam.getPhone(),
                memberCardQueryParam.getCardType());
        PageInfo<MemberCardSelectAllDTO> pageInfo = new PageInfo(mapList);
        return AjaxResponseBody.success(pageInfo);
    }

    //绑定vip卡
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResponseBody bindVipCard(Integer hotelId, String startCardId, String endCardId) {
        //校验
        if (null == hotelId) {
            throw new ServiceException("酒店id错误");
        }
        HotelInfo hotelInfo = hotelInfoMapper.selectByPrimaryKey(hotelId);
        if (null == hotelInfo) {
            throw new ServiceException("酒店不存在");
        }
        if (StringUtils.isBlank(startCardId) || !pattern.matcher(startCardId).find()) {
            throw new ServiceException("起始卡号错误");
        }
        if (StringUtils.isBlank(endCardId) || !pattern.matcher(endCardId).find()) {
            throw new ServiceException("截止卡号错误");
        }
        String startCardIdA = startCardId.substring(0, 6);
        String endCardIdA = endCardId.substring(0, 6);
        if (!startCardIdA.equals(endCardIdA)) {
            throw new ServiceException("版本批次错误");
        }
        String version = startCardIdA.substring(0, 2);
        String batch = startCardIdA.substring(2);
        Long startCardIdB = Long.valueOf(startCardId.substring(6));
        Long endCardIdB = Long.valueOf(endCardId.substring(6));
        if (startCardIdB > endCardIdB) {
            throw new ServiceException("起始卡号大于截止卡号");
        }
        //reids锁实现
        return redisUtil.runWithLock(redisLockVipCardOperating, 10, 10, () -> {
            //查询存在的激活卡数量
            QueryWrapper<MemberCard> queryWrapper = new QueryWrapper<MemberCard>()
                    .eq(MemberCard.VERSION_NUMBER, version)
                    .eq(MemberCard.BATCH_NUMBER, batch)
                    .between(MemberCard.SERIAL_NUMBER, startCardIdB, endCardIdB)
                    .ne(MemberCard.STATUS, 0);
            long activationCardNumber = memberCardMapper.selectCount(queryWrapper
            );
            if (activationCardNumber > 0) {
                List<MemberCard> memberCards = memberCardMapper.selectList(queryWrapper);
                StringJoiner stringJoiner = new StringJoiner(",");
                for (MemberCard memberCard : memberCards) {
                    stringJoiner.add(memberCard.getCardNo());
                }
                throw new ServiceException("存在" + activationCardNumber + "张已激活的卡:" + stringJoiner.toString());
            }
            //修改
            MemberCard memberCard = new MemberCard();
            memberCard.setHotelId(hotelId);
            memberCard.setStatus(1);
            int i = memberCardMapper.update(memberCard, new QueryWrapper<MemberCard>()
                    .eq(MemberCard.VERSION_NUMBER, version)
                    .eq(MemberCard.BATCH_NUMBER, batch)
                    .between(MemberCard.SERIAL_NUMBER, startCardIdB, endCardIdB)
                    .eq(MemberCard.STATUS, 0)
            );
            return AjaxResponseBody.success("修改记录" + i + "条");
        });
    }

    //解绑vip卡
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResponseBody unBindVipCard(String startCardId, String endCardId) {
        if (StringUtils.isBlank(startCardId) || !pattern.matcher(startCardId).find()) {
            throw new ServiceException("起始卡号错误");
        }
        if (StringUtils.isBlank(endCardId) || !pattern.matcher(endCardId).find()) {
            throw new ServiceException("截止卡号错误");
        }
        String startCardIdA = startCardId.substring(0, 6);
        String endCardIdA = endCardId.substring(0, 6);
        if (!startCardIdA.equals(endCardIdA)) {
            throw new ServiceException("版本批次错误");
        }
        String version = startCardIdA.substring(0, 2);
        String batch = startCardIdA.substring(2);
        Long startCardIdB = Long.valueOf(startCardId.substring(6));
        Long endCardIdB = Long.valueOf(endCardId.substring(6));
        if (startCardIdB > endCardIdB) {
            throw new ServiceException("起始卡号大于截止卡号");
        }
        //reids锁实现
        return redisUtil.runWithLock(redisLockVipCardOperating, 10, 10, () -> {
            //查询参数中已绑定的卡
            QueryWrapper<MemberCard> queryWrapper = new QueryWrapper<MemberCard>()
                    .eq(MemberCard.VERSION_NUMBER, version)
                    .eq(MemberCard.BATCH_NUMBER, batch)
                    .between(MemberCard.SERIAL_NUMBER, startCardIdB, endCardIdB)
                    .eq(MemberCard.STATUS, 2);
            long activationCardNumber = memberCardMapper.selectCount(queryWrapper);
            if (activationCardNumber > 0) {
                List<MemberCard> memberCards = memberCardMapper.selectList(queryWrapper);
                StringJoiner stringJoiner = new StringJoiner(",");
                for (MemberCard memberCard : memberCards) {
                    stringJoiner.add(memberCard.getCardNo());
                }
                throw new ServiceException("存在" + activationCardNumber + "张已绑定的卡:" + stringJoiner.toString());
            }
            //修改
            int i = memberCardMapper.unBindMemberCard(version, batch, startCardIdB, endCardIdB, 1);
            return AjaxResponseBody.success("修改记录" + i + "条");
        });
    }

    /**
     * vip卡退款V2
     *
     * @param orderHead
     * @param refundAmount
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refundAmountV2(OrderHead orderHead, Integer refundAmount) {
        //退款记录对象
        HashMap<String, Object> map = new HashMap<>();
        Integer cardType = VipCardTypeEnum.getCardTypeByOrderVipFlagValueThrowE(orderHead.getVipFlag());
        //修改卡余额
        UserMemberCard userMemberCard = userMemberCardService.getUserMemberCard(orderHead.getUserId(), cardType);
        if (Objects.isNull(userMemberCard)) {
            throw new ServiceException("vip卡绑定用户的记录不存在");
        }
        MemberCard memberCard = memberCardMapper.selectById(userMemberCard.getCardId());
        if (Objects.isNull(memberCard)) {
            throw new ServiceException("vip卡不存在");
        }
        UserMemberCardBill userMemberCardBill = userMemberCardBillMapper.selectOne(new QueryWrapper<UserMemberCardBill>()
                .eq(UserMemberCardBill.CARD_ID, userMemberCard.getCardId())
                .eq(UserMemberCardBill.ORDER_NO, orderHead.getOrderNo())
                .eq(UserMemberCardBill.TYPE, 1)
                .eq(UserMemberCardBill.STATUS, 1));
        if (null == userMemberCardBill) {
            throw new ServiceException("vip卡绑定用户的消费记录不存在");
        }
        Integer payAmount = userMemberCardBill.getPayAmount();
        Integer giveAmount = userMemberCardBill.getGiveAmount();
        Integer remainPayAmount = userMemberCard.getRemainPayAmount();
        Integer remainGiveAmount = userMemberCard.getRemainGiveAmount();
        if (refundAmount <= giveAmount) {
            userMemberCard.setRemainGiveAmount(remainGiveAmount + refundAmount);
        } else if (refundAmount <= (payAmount + giveAmount)) {
            userMemberCard.setRemainGiveAmount(remainGiveAmount + giveAmount);
            userMemberCard.setRemainPayAmount(remainPayAmount + (refundAmount - giveAmount));
        } else {
            throw new ServiceException("钱包的退款金额大于付款金额");
        }
        boolean update = userMemberCardService.update(userMemberCard, new UpdateWrapper<UserMemberCard>()
                .eq(UserMemberCard.ID, userMemberCard.getId())
                .eq(UserMemberCard.REMAIN_PAY_AMOUNT, remainPayAmount)
                .eq(UserMemberCard.REMAIN_GIVE_AMOUNT, remainGiveAmount));
        if (!update) {
            throw new ServiceException("vip卡钱包退款失败");
        }
        int i = userMemberCardBillMapper.update(null, new UpdateWrapper<UserMemberCardBill>()
                .set(UserMemberCardBill.STATUS, 2)
                .eq(UserMemberCardBill.ID, userMemberCardBill.getId())
        );
        if (i < 1) {
            throw new ServiceException("卡支付明细修改失败");
        }
        //保存退款记录
        map.put("checkIn", DateUtils.formatDate(orderHead.getCheckIn()));
        map.put("checkOut", DateUtils.formatDate(orderHead.getCheckOut()));
        map.put("count", orderHead.getDays());
        map.put("hotelName", orderHead.getSnapshotHotelName());
        MessageNoticeTemplate messageNoticeTemplate = messageNoticeTemplateMapper.selectTemplateValue("card.refund.order");
        map.put("remainAmount", BigDecimal.valueOf(userMemberCard.getRemainGiveAmount() + userMemberCard.getRemainPayAmount()).divide(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_DOWN));
        String content = FormatUtils.formatTemplate(messageNoticeTemplate.getContent(), map);
        //添加退款记录
        MemberCardDetail memberCardDetail = new MemberCardDetail();
        memberCardDetail.setUserId(userMemberCard.getUserId()).setContent(content).setIconUrl(messageNoticeTemplate.getIconUrl()).setCardType(memberCard.getCardType());
        int insert = memberCardDetailMapper.insert(memberCardDetail);
        if (insert < 1) {
            throw new ServiceException("退款记录保存失败");
        }
    }

    /**
     * 生成对应数量的会员卡
     *
     * @param count
     */
    @Override
    public void createMemberCard(Integer count, Integer cardType,Integer givenAmount, Integer saleType, Integer salePrice) {
        List<String> ids = getIdsByMaxCardNo(count, cardType);
        int enable = 0;
        if (1 == cardType) {
            ids = ids.stream().filter(e -> !e.contains("4")).collect(Collectors.toList());
        } else {
            enable = 1;
        }
        for (String disposeId : ids) {
            try {
                MemberCard memberCard = getMemberCard(disposeId, configService.getCardRule(cardType), cardType, enable);
                if (memberCard != null) {
                    memberCard.setSaleType(saleType);
                    memberCard.setSalePrice(salePrice);
                    memberCard.setRemainAmount(givenAmount);
                    baseMapper.insert(memberCard);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 通过会员卡id获取会员卡信息
     *
     * @param id
     * @return
     */
    @Override
    public MemberCard selectById(Integer id) {
        return baseMapper.selectById(id);
    }

    /**
     * 通过会员卡号获取会员卡
     *
     * @param cardNo
     * @return
     */
    @Override
    public MemberCard selectByCardNo(String cardNo) {
        return baseMapper.selectByCardNo(cardNo);
    }

    /**
     * 会员权益
     *
     * @return
     */
    @Override
    public Object advantage(MemberCardTypeParam param) {
        try {
            String value;
            switch (param.getCardType()) {
                case 1:
                    value = configService.getValue(ConfigKey.MEMBER_ADVANTAGE);
                    break;
                case 2:
                    value = configService.getValue(ConfigKey.MEMBER_ADVANTAGE_JIP);
                    break;
                default:
                    throw new ServiceException("卡类型错误");
            }
            if (ArgumentsCheckUtil.strIsNull(value)) {
                return getDefaultAdvantage();
            }
            return JSONObject.parseArray(value);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getDefaultAdvantage();
    }

    /**
     * 获取钱包说明
     *
     * @return
     */
    @Override
    public Object walletDesc(MemberCardTypeParam param) {
        try {
            String value;
            switch (param.getCardType()) {
                case 1:
                    value = configService.getValue(ConfigKey.WALLET_DESC);
                    break;
                case 2:
                    value = configService.getValue(ConfigKey.WALLET_DESC_JIP);
                    break;
                default:
                    throw new ServiceException("卡类型错误");
            }
            if (ArgumentsCheckUtil.strIsNull(value)) {
                return getDefaultWalletDesc();
            }
            return Splitters.splitToString(value, Splitters.ENTER);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getDefaultWalletDesc();
    }

    @Override
    public Integer update(MemberCard memberCard) {
        memberCard.setUpdateTime(new Date());
        return baseMapper.updateById(memberCard);
    }

    @Override
    public AjaxResponseBody selectServerAll(MemberCardServerQueryParam param, AccountInfo loginUser) {

        if (null == param.getPageNum()) {
            param.setPageNum(1);
        }
        if (null == param.getPageSize()) {
            param.setPageSize(10);
        }
        //1:甄选  2：精选
        Integer cardType = 1;
        if (param.getCardType() != null) {
            cardType = param.getCardType();
        }
        List<MemberCardSelectServerAllDTO> mapList = Lists.newArrayList();
        if (loginUser.getType() == AccountType.Administrator) {
            PageHelper.startPage(param.getPageNum(), param.getPageSize());
            mapList = memberCardMapper
                    .selectServerForManagementPage(param.getCardNo(),
                            param.getHotelId(),
                            param.getSalerName(),
                            param.getStatus(),
                            param.getPhone(),
                            cardType,
                            null);
        } else {
            List<Integer> salerIdList = accountVipSalerRelationService.listByChildrenAndMySelf(loginUser);
            PageHelper.startPage(param.getPageNum(), param.getPageSize());
            mapList = memberCardMapper.selectServerForManagementPage(param.getCardNo(),
                    param.getHotelId(),
                    param.getSalerName(),
                    param.getStatus(),
                    param.getPhone(),
                    cardType,
                    salerIdList);
        }
        PageInfo<MemberCardSelectServerAllDTO> pageInfo = PageInfo.of(mapList);


        return AjaxResponseBody.success(pageInfo);
    }

    @Override
    public AjaxResponseBody selectChoiceAll(MemberCardChoiceQueryParam param, AccountInfo loginUser) {
        //查询酒店的精选卡片
        if (null == param.getPageNum()) {
            param.setPageNum(1);
        }
        if (null == param.getPageSize()) {
            param.setPageSize(10);
        }
        if (loginUser.getType() == AccountType.HotelManager) {
            //得到酒店Id
//            List<HotelInfo> hotelInfoList = hotelInfoMapper.selectByOperator(loginUser.getId());
//            if (!CollectionUtils.isEmpty(hotelInfoList) && hotelInfoList.size() > 0) {
//                param.setHotelId(hotelInfoList.get(0).getId());
//            }
            HotelInfo hotelInfo = hotelInfoMapper.selectByHotelManager(loginUser.getId());
            if (null != hotelInfo) {
                param.setHotelId(hotelInfo.getId());
            }
        }
        //1:甄选  2：精选
        Integer cardType = 2;
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<MemberCardSelectChoiceAllDTO> mapList = memberCardMapper.selectChoiceForManagementPage(
                param.getCardNo(),
                param.getHotelId(),
                param.getPhone(),
                param.getStatus(),
                cardType
        );

        PageInfo<MemberCardSelectChoiceAllDTO> pageInfo = PageInfo.of(mapList);

        return AjaxResponseBody.success(pageInfo);
    }

    @Override
    public AjaxResponseBody bindChoiceCard(Integer hotelId, String startCardId, String endCardId) {

        //精选卡片绑定

        return bindVipCard(hotelId, startCardId, endCardId);
    }

    /**
     * 分页查询【优享】VIP卡 admin - app
     *
     * @param param       查询参数
     * @param accountInfo 操作人
     * @return
     */
    @Override
    public CommonResult<CommonPage<AppMemberCardDTO>> pageMinVipList(QueryMinMemberCardParam param, AccountInfo accountInfo) {

        if (accountInfo.getType() != AccountType.Administrator) {
            throw new OftenFiledException("没有权限查看", CommonResult.NO_PERMISSION);
        }
        CommonPage<AppMemberCardDTO> memberCardDTOCommonPage = new CommonPage<>();

        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<AppMemberCardDTO> memberCardDTOList = memberCardMapper.selectMinVipList(param);
        if (!CollectionUtils.isEmpty(memberCardDTOList)) {
            memberCardDTOCommonPage = CommonPage.restPage(param.getPageNum(), param.getLastId(), memberCardDTOList);
        }
        return CommonResult.success(memberCardDTOCommonPage);
    }

    /**
     * 通过卡商id和卡商类型获取该卡商对应的酒店id集合
     *
     * @param salerId   卡商id
     * @param salerType 卡商类型(可不传)0:运营商 1：服务商 2：卡商
     * @param cardType  卡类型1:甄选  2：精选
     * @return
     */
    @Override
    public List<MemberCard> selectBySalerIdAndSalerType(Integer salerId, Integer salerType, Integer cardType) {
        QueryWrapper<MemberCard> wrapper = new QueryWrapper<>();
        wrapper.eq(MemberCard.SALER_ID, salerId);
        wrapper.eq(MemberCard.CARD_TYPE, cardType);
        if (null != salerType) {
            wrapper.eq(MemberCard.SALER_TYPE, salerType);
        }
        return baseMapper.selectList(wrapper);
    }

    /**
     * web端充值
     *
     * @param param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean webRecharge(MemberCardRechargeParam param) {
        Date date = new Date();
        //1.通过会员卡号查询会员卡
        MemberCard memberCard = baseMapper.selectOne(new QueryWrapper<MemberCard>()
                .eq(MemberCard.CARD_NO, param.getCardNo())
                .eq(MemberCard.CARD_TYPE, 2).last("limit 1"));
        Arguments.beanIsNull(memberCard, "该会员卡不存在");
        //2.查询该卡绑定用户
        UserMemberCard userMemberCard = userMemberCardService.getOne(new QueryWrapper<UserMemberCard>()
                .eq(UserMemberCard.CARD_ID, memberCard.getId())
                .eq(UserMemberCard.CARD_TYPE, 2).last("limit 1"));
        Arguments.beanIsNull(userMemberCard, "该会员卡未绑定用户");
        //3.添加充值记录表
        RechargeRecord rechargeRecord = new RechargeRecord();
        rechargeRecord.setCardNo(memberCard.getCardNo());
        rechargeRecord.setGiveAmount(param.getGiveAmount());
        rechargeRecord.setPhone(userMemberCard.getPhone());
        rechargeRecord.setOrderNo(IdWorkerUtil.nextStrId());
        rechargeRecord.setUserId(userMemberCard.getUserId());
        rechargeRecord.setPayAmount(param.getPayAmount());
        rechargeRecord.setType(RechangeRecordEnum.WEB_PAY.value());
        rechargeRecord.setOrderDesc(RechangeRecordEnum.WEB_PAY.desc());
        rechargeRecord.setPaymentMethod(OrderInfoMattressPayTypeEnum.OFFLINE.value());
        rechargeRecord.setStatus(RechargeRecordStatus.postPay);
        rechargeRecord.setCreatedTime(date);
        rechargeRecord.setUpdatedTime(date);
        //4.充值记录插入
        Arguments.isFalse(rechargeRecordService.save(rechargeRecord), "充值记录添加失败");
        //5.会员卡余额添加
        UserMemberCardAddAmountParam cardParam = new UserMemberCardAddAmountParam();
        cardParam.setUserId(rechargeRecord.getUserId());
        cardParam.setPayAmount(param.getPayAmount());
        cardParam.setGiveAmount(param.getGiveAmount());
        cardParam.setType(UserMemberCardBillType.PAY.value());
        cardParam.setRemark(UserMemberCardBillType.PAY.desc());
        cardParam.setOrderNo(rechargeRecord.getOrderNo());
        cardParam.setCardType(2);
        Arguments.isFalse(userMemberCardService.addAmount(cardParam), "增加会员卡余额异常");
        //增加一条模板记录
        UserMemberCard nowUserMemberCard = userMemberCardService.getOne(new QueryWrapper<UserMemberCard>()
                .eq(UserMemberCard.CARD_ID, memberCard.getId())
                .eq(UserMemberCard.CARD_TYPE, 2).last("limit 1"));
        Map<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("amount", FormatUtils.fenToYuan(param.getPayAmount()));
        paramMap.put("remainAmount", FormatUtils.fenToYuan(nowUserMemberCard.getRemainGiveAmount() + nowUserMemberCard.getRemainPayAmount()));
        Map<String, String> map = templateService.commonValue(paramMap, MessageTemplate.CARD_PAY);
        MemberCardDetail detail = new MemberCardDetail();
        detail.setUserId(rechargeRecord.getUserId());
        detail.setContent(map.get("content"));
        detail.setIconUrl(map.get("iconUrl"));
        detail.setCreateTime(new Date());
        detail.setCardType(2);
        detail.setCreateTime(date);
        Arguments.isFalse(memberCardDetailService.save(detail), "模板写入失败");
        return true;
    }

    @Override
    public Map<String, MemberCard> getMapList(List<String> cardNoList) {

        List<MemberCard> list = this.baseMapper.selectList(new QueryWrapper<MemberCard>().in(MemberCard.CARD_NO, cardNoList));
        Map<String, MemberCard> memberCardMap = Maps.newHashMap();
        if (!CollectionUtils.isEmpty(list)) {
            memberCardMap = list.stream().collect(Collectors.toMap(MemberCard::getCardNo, memberCard -> memberCard));
        }
        return memberCardMap;
    }

    @Override
    public AjaxResponseBody bindServerVipCard(MemberCardBindParam param) {
        //校验
        if (null == param.getHotelId()) {
            throw new ServiceException("酒店id错误");
        }
        if (null == param.getSalerId()) {
            throw new ServiceException("运营商/卡商ID不能为空");
        }
        if (null == param.getSalerType()) {
            throw new ServiceException("运营商/卡商ID类型不能为空");
        }
        HotelInfo hotelInfo = hotelInfoMapper.selectByPrimaryKey(param.getHotelId());
        if (null == hotelInfo) {
            throw new ServiceException("酒店不存在");
        }
        if (StringUtils.isBlank(param.getStartCardId()) || !pattern.matcher(param.getStartCardId()).find()) {
            throw new ServiceException("起始卡号错误");
        }
        if (StringUtils.isBlank(param.getEndCardId()) || !pattern.matcher(param.getEndCardId()).find()) {
            throw new ServiceException("截止卡号错误");
        }
        String startCardIdA = param.getStartCardId().substring(0, 6);
        String endCardIdA = param.getEndCardId().substring(0, 6);
        if (!startCardIdA.equals(endCardIdA)) {
            throw new ServiceException("版本批次错误");
        }
        String version = startCardIdA.substring(0, 2);
        String batch = startCardIdA.substring(2);
        Long startCardIdB = Long.valueOf(param.getStartCardId().substring(6));
        Long endCardIdB = Long.valueOf(param.getEndCardId().substring(6));
        if (startCardIdB > endCardIdB) {
            throw new ServiceException("起始卡号大于截止卡号");
        }
        //reids锁实现
        return redisUtil.runWithLock(redisLockVipCardOperating, 10, 10, () -> {
            //查询存在的激活卡数量
            QueryWrapper<MemberCard> queryWrapper = new QueryWrapper<MemberCard>()
                    .eq(MemberCard.VERSION_NUMBER, version)
                    .eq(MemberCard.BATCH_NUMBER, batch)
                    .between(MemberCard.SERIAL_NUMBER, startCardIdB, endCardIdB)
                    .ne(MemberCard.STATUS, 0);
            long activationCardNumber = memberCardMapper.selectCount(queryWrapper
            );
            if (activationCardNumber > 0) {
                List<MemberCard> memberCards = memberCardMapper.selectList(queryWrapper);
                StringJoiner stringJoiner = new StringJoiner(",");
                for (MemberCard memberCard : memberCards) {
                    stringJoiner.add(memberCard.getCardNo());
                }
                throw new ServiceException("存在" + activationCardNumber + "张已激活的卡:" + stringJoiner.toString());
            }
            //修改
            MemberCard memberCard = new MemberCard();
            memberCard.setHotelId(param.getHotelId());
            memberCard.setSalerId(param.getSalerId());
            if (param.getSalerType() == AccountType.OperateMerchant || param.getSalerType() == AccountType.MinOperateMerchant) {
                memberCard.setSalerType(0);
            } else if (param.getSalerType() == AccountType.VipCardMerchant || param.getSalerType() == AccountType.MinVipCardMerchant) {
                memberCard.setSalerType(2);
            }
            memberCard.setStatus(1);
            int i = memberCardMapper.update(memberCard, new QueryWrapper<MemberCard>()
                    .eq(MemberCard.VERSION_NUMBER, version)
                    .eq(MemberCard.BATCH_NUMBER, batch)
                    .between(MemberCard.SERIAL_NUMBER, startCardIdB, endCardIdB)
                    .eq(MemberCard.STATUS, 0)
            );
            return AjaxResponseBody.success("成功修改记录" + i + "条");
        });
    }

    /**
     * 分页查询【优享】VIP卡[查询还需要改动]
     *
     * @param param     查询参数
     * @param loginUser 操作人
     * @return
     */
    @Override
    public AjaxResponseBody selectMinVipCard(MinMemberCardQueryParam param, AccountInfo loginUser) {
        if (null == param.getPageNum()) {
            param.setPageNum(1);
        }
        if (null == param.getPageSize()) {
            param.setPageSize(10);
        }
        //2：【优享】VIP卡
        Integer cardType = 2;
        List<MemberCardSelectServerAllDTO> mapList = Lists.newArrayList();
        if (loginUser.getType() == AccountType.Administrator) {
            PageHelper.startPage(param.getPageNum(), param.getPageSize());
            mapList = memberCardMapper
                    .selectServerForManagementPage(param.getCardNo(),
                            param.getHotelId(),
                            param.getSalerName(),
                            param.getStatus(),
                            param.getPhone(),
                            cardType,
                            null);
        } else {
            List<Integer> salerIdList = accountVipSalerRelationService.listByChildrenAndMySelf(loginUser);
            //查询酒店ID
            if (loginUser.getType() == AccountType.HotelManager) {
                List<HotelInfo> hotelInfoList = hotelInfoMapper.selectByOperator(loginUser.getId());
                if (!CollectionUtils.isEmpty(hotelInfoList)) {
                    param.setHotelId(hotelInfoList.get(0).getId());
                    salerIdList = null;
                }
            }
            PageHelper.startPage(param.getPageNum(), param.getPageSize());
            mapList = memberCardMapper.selectServerForManagementPage(param.getCardNo(),
                    param.getHotelId(),
                    param.getSalerName(),
                    param.getStatus(),
                    param.getPhone(),
                    cardType,
                    salerIdList);
        }
        PageInfo<MemberCardSelectServerAllDTO> pageInfo = PageInfo.of(mapList);

        return AjaxResponseBody.success(pageInfo);

    }

    /**
     *
     * @param param 绑定输入参数
     * @return
     */
    @Override
    public AjaxResponseBody bindMinVipCard(MinMemberCardBindParam param) {

        return this.bindServerVipCard(MyBeanUtils.convert(param, MemberCardBindParam.class));
    }

    /**
     * 运营商 给 卡商 划拨卡号
     *
     * @param param 输入参数
     * @return
     */
    @Override
    public AjaxResponseBody bindMinVipCardBusiness(MinMemberCardBusinessBindParam param, AccountInfo loginUser) {

        if (!pattern.matcher(param.getStartCardId()).find()) {
            throw new ServiceException("起始卡号错误");
        }
        if (!pattern.matcher(param.getEndCardId()).find()) {
            throw new ServiceException("截止卡号错误");
        }
        String startCardIdA = param.getStartCardId().substring(0, 6);
        String endCardIdA = param.getEndCardId().substring(0, 6);
        if (!startCardIdA.equals(endCardIdA)) {
            throw new ServiceException("版本批次错误");
        }
        String version = startCardIdA.substring(0, 2);
        String batch = startCardIdA.substring(2);

        Long startCardIdB = Long.valueOf(param.getStartCardId().substring(6));
        Long endCardIdB = Long.valueOf(param.getEndCardId().substring(6));
        if (startCardIdB > endCardIdB) {
            throw new ServiceException("起始卡号大于截止卡号");
        }
        //查询该卡号区间是否是该运营商所拥有的的
        QueryWrapper<MemberCard> queryWrapper = new QueryWrapper<MemberCard>()
                .eq(MemberCard.VERSION_NUMBER, version)
                .eq(MemberCard.BATCH_NUMBER, batch)
                .between(MemberCard.SERIAL_NUMBER, startCardIdB, endCardIdB)
                .eq(MemberCard.SALER_ID, loginUser.getId());
        long selectCount = memberCardMapper.selectCount(queryWrapper);
        if(selectCount == 0L){
           throw new ServiceException("该运营商没有此卡号段");
        }

        //更新卡号的绑定者（下面的卡商，需要验证）
        MemberCard memberCard = new MemberCard();
        AccountVipSalerRelation accountVipSalerRelation = accountVipSalerRelationService
                .selectByAccountId( param.getSalerId(), 2 , AccountType.MinOperateMerchant);
        if(null == accountVipSalerRelation){
            throw new ServiceException( "卡商ID不存在" );
        }
        memberCard.setSalerId(param.getSalerId());
        memberCard.setSalerType(2);
        int i = memberCardMapper.update(memberCard, new QueryWrapper<MemberCard>()
                .eq(MemberCard.VERSION_NUMBER, version)
                .eq(MemberCard.BATCH_NUMBER, batch)
                .between(MemberCard.SERIAL_NUMBER, startCardIdB, endCardIdB)
        );
        //返回信息
        return AjaxResponseBody.success("成功划拨记录" + i + "条");
    }

    /**
     * 会员卡代卖列表
     *
     * @param param
     * @return
     */
    @Override
    public PageResult<MemberCardHelpPayListResult> helpPayList(MemberCardHelpPayListParam param) {
        Map<String, Object> map = new HashMap<>();
        if (AccountType.Administrator != param.getType()) {
            map.put("id", param.getId());
        }
        if (StrUtil.isNotBlank(param.getCardNo())) {
            map.put("cardNo", param.getCardNo());
        }
        if (StrUtil.isNotBlank(param.getPhone())) {
            map.put("phone", param.getPhone());
        }
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<MemberCardHelpPayListResult> results = baseMapper.selectHelpPayList(map);
        return PageResult.getPageResult(results);
    }

    /**
     * 会员卡代卖
     *
     * @param cardNo
     * @param loginUser
     * @return
     */
    @Override
    public Boolean helpPay(String cardNo, AccountInfo loginUser) {
        //查询当前登录人下的会员号
        List<String> cardNos = baseMapper.selectCardNoBySalerId(loginUser.getId());
        Arguments.isTrue(CollUtil.isEmpty(cardNos), "您还没有签约会员卡");
        Arguments.isFalse(cardNos.contains(cardNo), "非本人会员卡");
        MemberCard memberCard = baseMapper.selectOne(new QueryWrapper<MemberCard>().eq(MemberCard.CARD_NO, cardNo).eq(MemberCard.CARD_TYPE, 2).last("limit 1"));
        Arguments.beanIsNull(memberCard, "该会员卡不存在");
        //查询该卡是否已经绑定用户
        UserMemberCard userMemberCard = userMemberCardService.selectByCardId(memberCard.getId(), memberCard.getCardType());
        Arguments.isTrue(null != userMemberCard, "该卡已绑定用户");
        Arguments.isTrue(1 == memberCard.getHelpPay(), "该卡已代卖");
        memberCard.setHelpPay(1);
        memberCard.setUpdateTime(new Date());
        Arguments.isFalse(1 == baseMapper.updateById(memberCard), "会员卡代卖异常");
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean helpBusinessPay(String startCardNo, String endCardNo, AccountInfo loginUser) {

        List<String> cardNos = baseMapper.selectCardNoBySalerId(loginUser.getId());
        Arguments.isTrue(CollUtil.isEmpty(cardNos), "你的会员卡为空");
        //验证起始会员卡号即可么？是的
        Arguments.isFalse(cardNos.contains(startCardNo), "非本人会员卡");
        Arguments.isFalse(cardNos.contains(endCardNo), "非本人会员卡");
        List<MemberCard> memberCardList = baseMapper.selectList(new QueryWrapper<MemberCard>()
                .between(MemberCard.CARD_NO, startCardNo, endCardNo)
                .eq(MemberCard.CARD_TYPE, 2));
        if(CollUtil.isEmpty(memberCardList)){
            throw new ServiceException("该会员卡不存在");
        }
        memberCardList.forEach(memberCard -> {
            UserMemberCard userMemberCard = userMemberCardService.selectByCardId(memberCard.getId(), memberCard.getCardType());
            Arguments.isTrue(null != userMemberCard, "【"+memberCard.getCardNo()+"】:该卡已绑定用户");
            Arguments.isTrue(1 == memberCard.getHelpPay(), "【"+memberCard.getCardNo()+"】:该卡已代卖");
            memberCard.setHelpPay(1);
            memberCard.setUpdateTime(new Date());
        });
        Arguments.isFalse(this.updateBatchById(memberCardList), "运营商会员卡代卖异常");
        return true;
    }

    @Override
    public String getRandomCardNoByAccount(AccountInfo loginUser) {

        //查询该商家下已经激活的会员卡。除去代卖卡
        List<MemberCard> memberCardList = baseMapper.selectList(new QueryWrapper<MemberCard>()
                .eq(MemberCard.CARD_TYPE, 2)
                .eq(MemberCard.SALER_ID, loginUser.getId())
                .eq(MemberCard.STATUS, 1)
                .eq(MemberCard.HELP_PAY, 0));
        Arguments.isTrue(CollUtil.isEmpty(memberCardList), "你的已激活会员卡为空");
        List<Integer> randomNum = CommonRandomUtils.random(memberCardList.size(), 1);
        if(!CollUtil.isEmpty(randomNum)){
            int index = randomNum.get(0);
            MemberCard memberCard = memberCardList.get(index);
            return memberCard.getCardNo();
        }
        return null;
    }

    @Override
    public AjaxResponseBody selectForHotelServerManagerPage(MemberCardServerQueryParam memberCardQueryParam, AccountInfo loginUser) {

        Long count = memberCardMapper.countCardByHotelId(memberCardQueryParam.getHotelId(),
                memberCardQueryParam.getCardType());

        AjaxResponseBody ajaxResponseBody = selectServerAll(memberCardQueryParam, loginUser);
        HashMap<String, Object> map = new HashMap<>();
        map.put("count", count);
        map.put("list", ajaxResponseBody.getBody());
        return AjaxResponseBody.success(map);
    }

    /**
     * 查询该用户的会员卡对应的酒店账户id和下单手机号
     *
     * @param userId
     * @param cardType 1甄选，2精选
     * @return
     */
    @Override
    public AccountCardDTO selectOperatorIdAndCardNoByUserId(Integer userId, Integer cardType) {
        return baseMapper.selectOperatorIdAndCardNoByUserId(userId, cardType);
    }

    /**
     * 通过会员卡和类型查询会员卡对象
     *
     * @param cardNo    会员卡号
     * @param salerType 0:运营商 1：服务商 2：卡商
     * @param cardType  1：大V 2：小V
     * @return
     */
    @Override
    public MemberCard selectByCardNoAndType(String cardNo, Integer salerType, Integer cardType) {
        return baseMapper.selectOne(new QueryWrapper<MemberCard>()
                .eq(MemberCard.CARD_NO, cardNo)
                .eq(MemberCard.SALER_TYPE, salerType)
                .eq(MemberCard.CARD_TYPE, cardType)
                .last("limit 1"));
    }


    private Object getDefaultWalletDesc() {
        List<String> list = Lists.newArrayList();
        list.add("1. 臻享钱包属于夜鱼臻享会员专属功能，功能仅对臻享会员开放");
        list.add("2. 臻享钱包余额仅支持臻选酒店专区预订酒店时使用");
        list.add("3. 臻享钱包充值金额享受臻享会员专属优惠活动");
        list.add("4. 臻享钱包充值余额享不支持提现及退款");
        list.add("5. 若有疑问请拨打客服热线：400-8263595 客服时间：9：00 - 17:00");
        list.add("6. 夜鱼快宿保留该活动最终解释权");
        return list;
    }

    private List<Map<String, Object>> getDefaultAdvantage() {
        List<Map<String, Object>> result = Lists.newArrayList();
        Map<String, Object> detailMap = Maps.newHashMap();
        detailMap.put("title", "五折订房");
        detailMap.put("pic", "http://yeyu-kuaisu.oss-cn-hangzhou.aliyuncs.com/card/card_order_gray.png");
        detailMap.put("picIcon", "http://yeyu-kuaisu.oss-cn-hangzhou.aliyuncs.com/card/5zhedingfang@3x.png");
        detailMap.put("url", "https://kuaisutest.chengguokj.com/h5/vip/equity/app");
        List<String> list = Lists.newArrayList();
        list.add("1. 臻选酒店：夜鱼臻享会员可以享受夜鱼联盟精选的品质酒店，在享受超高性价比的同时享受高品质酒店");
        list.add("2. 臻享钱包：夜鱼臻享会员专享的电子钱包，享受会员充值优惠等活动");
        detailMap.put("advantage", list);

        Map<String, Object> detailMap2 = Maps.newHashMap();
        detailMap2.put("title", "甄享钱包");
        detailMap2.put("pic", "http://yeyu-kuaisu.oss-cn-hangzhou.aliyuncs.com/card/card_wallet_gray.png");
        detailMap2.put("picIcon", "http://yeyu-kuaisu.oss-cn-hangzhou.aliyuncs.com/card/zhenxiangqianbao@3x.png");
        detailMap2.put("url", "https://kuaisutest.chengguokj.com/h5/vip/equity/app");
        List<String> list2 = Lists.newArrayList();
        list2.add("1. 臻享钱包：夜鱼臻享会员专享的电子钱包，享受会员充值优惠等活动");
        detailMap2.put("advantage", list2);

        Map<String, Object> detailMap3 = Maps.newHashMap();
        detailMap3.put("title", "活动特权");
        detailMap3.put("pic", "http://yeyu-kuaisu.oss-cn-hangzhou.aliyuncs.com/card/card_activity_gray.png");
        detailMap3.put("picIcon", "http://yeyu-kuaisu.oss-cn-hangzhou.aliyuncs.com/card/huodtequan@3x.png");
        detailMap3.put("url", "https://kuaisutest.chengguokj.com/h5/vip/equity/app");
        List<String> list3 = Lists.newArrayList();
        list3.add("1. 活动特权：夜鱼臻享会员享受更多活动特权");
        detailMap3.put("advantage", list3);

        Map<String, Object> detailMap4 = Maps.newHashMap();
        detailMap4.put("title", "更多特权敬请期待");
        detailMap4.put("pic", "http://yeyu-kuaisu.oss-cn-hangzhou.aliyuncs.com/card/card_more_gray.png");
        detailMap4.put("picIcon", "http://yeyu-kuaisu.oss-cn-hangzhou.aliyuncs.com/card/gengduotequan@3x.png");
        detailMap4.put("url", "https://kuaisutest.chengguokj.com/h5/vip/equity/app");
        List<String> list4 = Lists.newArrayList();
        list4.add("1. 夜鱼联盟即将推出更多活动，为夜鱼臻享会员提供更多权益");
        detailMap4.put("advantage", list4);

        result.add(detailMap);
        result.add(detailMap2);
        result.add(detailMap3);
        result.add(detailMap4);
        return result;
    }

    /**
     * 获取一定数量的卡号
     *
     * @param amount
     * @return
     */
    private List<String> getIdsByMaxCardNo(Integer amount, Integer cardType) {
        try {
            CardNoResult cardNoResult = baseMapper.selectCardNo(cardType);
            if (null == cardNoResult) {
                if (baseMapper.selectList(new QueryWrapper<MemberCard>().eq(MemberCard.CARD_TYPE, cardType)).size() == 0) {
                    String cardNo = configService.getCardRule(cardType) + "0000000000";
                    cardNoResult = new CardNoResult(cardNo, "0000000000");
                } else {
                    throw new ServiceException("查询最大卡号失败");
                }
            }
            int intCardNo = Integer.valueOf(cardNoResult.getTenCardNo());
            List<String> ids = Lists.newArrayList();
            for (int i = 0; i < amount; i++) {
                intCardNo += 1;
                ids.add(getTenStr(intCardNo));
            }
            return ids;
        } catch (ServiceException e) {
            throw new ServiceException(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("生成卡号失败");
        }
    }

    /**
     * 获取十位的字符串不够补0
     *
     * @param cardNo
     * @return
     */
    private String getTenStr(Integer cardNo) {
        String strCardNo = String.valueOf(cardNo);
        StringBuilder sb = new StringBuilder();
        if (strCardNo.length() < 10) {
            int count = 10 - strCardNo.length();
            for (int i = 0; i < count; i++) {
                sb.append("0");
            }
            sb.append(strCardNo);
        } else {
            throw new ServiceException("10位卡号已经使用完毕");
        }
        return sb.toString();
    }

    private MemberCard getMemberCard(String id, String prefix, Integer cardType, int enable) {
        try {
            MemberCard memberCard = new MemberCard();
            if (ArgumentsCheckUtil.strIsNull(id)) {
                throw new ServiceException("卡号为空");
            }
            memberCard.setCardNo(prefix + id);
            String password = getPassword(id);
            memberCard.setPassword(password);
            String securityCode = Utility.getFigureRandom(3);
            memberCard.setSecurityCode(securityCode);
            memberCard.setEnable(enable);
            memberCard.setVersionNumber(prefix.substring(0, 2));
            memberCard.setBatchNumber(prefix.substring(2));
            memberCard.setSerialNumber(Long.valueOf(id));
            memberCard.setStatus(0);
            memberCard.setCardType(cardType);
            Date date = new Date();
            memberCard.setCreateTime(date);
            memberCard.setUpdateTime(date);
            return memberCard;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String getPassword(String cardNo) {
        String password = InvateCode.toSerialCode(Long.valueOf(cardNo.substring(cardNo.length() - 6)));
        if (password.length() > 6) {
            password = password.substring(1, 7);
        }
        return password;
    }


}
